package com.tools.app.sdk;

import android.text.TextUtils;
import android.util.Log;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.hm.ads.sdk.HmAdsSDK;
import com.hm.app.BuildConfig;
import com.hm.base.android.mob.AMApplication;
import com.tools.app.AppApplication;
import com.tools.app.AppConstant;

import java.util.ArrayList;

/**
 * <p>
 * Google Analytics
 * 包括了打点和一些基础的东西
 * </p>
 *
 * @author: yibin
 * @date: 16-6-22.
 */
public class GoogleAnalyticsImpl {
    private final static String TAG = "GoogleAnalyticsImpl";
    private final static String REFERRER_DEFAULT = "utm_source=hope&utm_medium=hope&utm_campaign=hope";
    private final static String REFERRER_CHANNEL = "default";
    private final static int MAX_GAHIT_CACHE = 10;
    private AMApplication context;
    private GoogleAnalytics analytics;
    private Tracker tracker;
    private boolean isDebug;
    private ArrayList<GAHit> cacheGAHits;
    private String gaReferrer = REFERRER_DEFAULT;
    private String referrerChannel = REFERRER_CHANNEL;

    public GoogleAnalyticsImpl(AppApplication context) {
        this.context = context;
        //设置debug日志
        setDebug(context.getSharedPrefManager().getKeyOpenDeveloper() || BuildConfig.DEBUG);

        if (!TextUtils.isEmpty(AppConstant.GA_UA)) {
            analytics = GoogleAnalytics.getInstance(context);
            tracker = analytics.newTracker(AppConstant.GA_UA);
            tracker.enableAdvertisingIdCollection(true);
            //这里存在问题，发现，在Release时永远不上报，但是因为,我们不看GA的奔溃日志，所以这里直接修改城false。
            tracker.enableExceptionReporting(false);
            //页面追踪，要自定义类名时，需要关闭改为false。。待定验证
            tracker.enableAutoActivityTracking(true);
        }
    }

    public Tracker getTracker() {
        return tracker;
    }

    /**
     * 注解这个方法现在不推荐使用
     *
     * @param categoryId
     * @param actionId
     * @param labelId
     * @param value
     */
    public void record(String categoryId, String actionId, String labelId, Long value) {
        console(categoryId, actionId, labelId, value);

        if (getTracker() == null) {
            return;
        }

        GAHit gaHit = new GAHit(categoryId, actionId, labelId, value);
        if (REFERRER_DEFAULT.equals(getReferrer()) && !isDebug()) {
            if (cacheGAHits == null) {
                cacheGAHits = new ArrayList<>();
            }
            if (cacheGAHits.size() >= MAX_GAHIT_CACHE) {
                checkCacheToRecord(gaHit);
            } else {
                cacheGAHits.add(gaHit);
            }
        } else {
            checkCacheToRecord(gaHit);
        }
    }

    public void record(String categoryId, String actionId, String labelId) {
        record(categoryId, actionId, labelId, null);
    }

    private void checkCacheToRecord(GAHit gaHit) {
        //如果存在referrer,先发送缓存中的打点记录
        if (cacheGAHits != null && cacheGAHits.size() > 0) {
            for (GAHit cacheGAHit : cacheGAHits) {
                sendGAHit(cacheGAHit);
            }
            cacheGAHits.clear();
            cacheGAHits = null;
        }
        sendGAHit(gaHit);
    }

    private void sendGAHit(GAHit gaHit) {
        HitBuilders.EventBuilder builder = new HitBuilders.EventBuilder()
                .setCategory(gaHit.categoryId)
                .setAction(gaHit.actionId)
                .setCustomDimension(1, getReferrerChannel())
                .setCampaignParamsFromUrl(getReferrer());
        if (gaHit.labelId != null) {
            builder.setLabel(gaHit.labelId);
        }
        if (gaHit.value != null) {
            builder.setValue(gaHit.value);
        }
        getTracker().send(builder.build());
    }

    /**
     * GA屏幕浏览日志
     *
     * @param screenName
     */
    public void recordScreenTrail(String screenName) {
        if (getTracker() == null) {
            return;
        }
        consoleScreen(screenName);
        getTracker().setScreenName(screenName);
        getTracker().send(new HitBuilders.ScreenViewBuilder().build());
    }

    private String getReferrerChannel() {
        if (!REFERRER_CHANNEL.equals(referrerChannel)) {
            return referrerChannel;
        }
        HmAdsSDK hmAdsSDK = HmAdsSDK.getInstance();
        if (hmAdsSDK == null) {
            return referrerChannel;
        }
        String referrer = hmAdsSDK.getReferrerChannel();
        if (!TextUtils.isEmpty(referrer)) {
            referrerChannel = referrer;
        }
        return referrerChannel;
    }

    private String getReferrer() {
        if (!REFERRER_DEFAULT.equals(gaReferrer)) {
            return gaReferrer;
        }
        String referrer = ((AppApplication) context).getSharedPrefManager().getReferrerForGA();
        if (!TextUtils.isEmpty(referrer)) {
            gaReferrer = referrer;
        }
        return gaReferrer;
    }

    private void consoleScreen(String categoryId) {
        console(categoryId, " ", " ", null);
    }

    private void console(String categoryId, String actionId, String labelId, Long value) {
        if (isDebug()) {
            if (value != null) {
                Log.i(TAG, categoryId + " | " + actionId + " | " + labelId + " | " + value.toString() + " |");
            } else {
                Log.i(TAG, categoryId + " | " + actionId + " | " + labelId + " | ");
            }
        }
    }

    private boolean isDebug() {
        return isDebug;
    }

    private void setDebug(boolean debug) {
        isDebug = debug;
    }

    private class GAHit {

        String categoryId;
        String actionId;
        String labelId;
        Long value;

        private GAHit(String categoryId, String actionId, String labelId, Long value) {
            this.categoryId = categoryId;
            this.actionId = actionId;
            this.labelId = labelId;
            this.value = value;
        }

    }
}
